package com.taotao.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.taotao.common.utils.CookieUtils;
import com.taotao.manage.pojo.ItemVO;
import com.taotao.web.service.ItemService;
import com.taotao.web.service.OrderService;
import com.taotao.web.service.UserService;
import com.taotao.web.thread.UserThreadLocal;
import com.taotao.web.vo.CommonResult;
import com.taotao.web.vo.Order;
import com.taotao.web.vo.User;

@Controller
@RequestMapping("order")
public class OrderController {
	
	@Autowired
	private ItemService itemService;
	
	@Autowired
	private UserService userService;	
	
	@Autowired
	private OrderService orderService;
	
	@RequestMapping(value = "{id}",method = RequestMethod.GET)
	public String toOrder(Model model,@PathVariable("id")Long id){
		//根据id查询商品详情
		ItemVO itemVO = itemService.showItem(id);
		model.addAttribute("item", itemVO);
		return "order";
	}
	
	//@RequestMapping(value = "submit",method = RequestMethod.POST)
	@PostMapping("submit")
	@ResponseBody
	public CommonResult createOrder(Order order,HttpServletRequest req){
		try {
			User user = UserThreadLocal.get();
			order.setUserId(user.getId());
			order.setBuyerNick(user.getUsername());
			return this.orderService.save(order);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@RequestMapping(value = "success",method = RequestMethod.GET)
	public String toSuccess(@RequestParam("id")String id,Model model){
		Order order = orderService.queryOrderById(id);
		model.addAttribute("order", order);
		model.addAttribute("date", new DateTime().plusDays(2).toString("MM月dd日"));
		return "success";
	}
}
